package com.losdun.web.controller.app;

import com.losdun.common.annotation.Anonymous;
import com.losdun.common.config.LosdunConfig;
import com.losdun.common.core.controller.BaseController;
import com.losdun.common.core.domain.AjaxResult;
import com.losdun.common.core.domain.entity.SysDictData;
import com.losdun.common.utils.StringUtils;
import com.losdun.common.utils.file.FileUploadUtils;
import com.losdun.common.utils.file.FileUtils;
import com.losdun.framework.config.ServerConfig;
import com.losdun.system.service.ISysConfigService;
import com.losdun.system.service.ISysDictTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/9/19
 **/
@RestController
@RequestMapping("/app/system")
@Slf4j
public class AppSystemController extends BaseController {

    @Autowired
    ISysConfigService configService;

    @Autowired
    ISysDictTypeService dictTypeService;

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";
    /**
     * 根据参数键名查询参数值
     */
    @GetMapping(value = "/config/{configKey}")
    @Anonymous
    public AjaxResult getConfigKey(@PathVariable String configKey)
    {
        return AjaxResult.success().put("data",configService.selectConfigByKey(configKey));
    }
    @Anonymous
    @GetMapping(value = "/dict/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType)
    {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return success(data);
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = LosdunConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }
}
